import 'dart:ui';

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_shell/config/modules_config.dart';
import 'package:flutter_lang/app_locales.dart';
import 'package:flutter_lang/flutter_lang.dart';
import 'package:flutter_lifecycle_base/base_state_widget.dart';
import 'package:flutter_theme/theme.dart';
import 'package:oktoast/oktoast.dart';
import 'package:route_manager/app_config.dart';
import 'package:route_manager/route_bridge.dart';
import 'config/main_lang_config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  SystemUiOverlayStyle systemUiOverlayStyle =
      SystemUiOverlayStyle(statusBarColor: Colors.transparent);
  SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);

  await SpUtil.getInstance();

  runApp(MainApp());
}


class MainApp extends StatefulWidget {
  @override
  _MainAppState createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  LanguageConfig _languageConfig;
  LocalizationsDelegate _localeOverrideDelegate;
  List<String> _paths;
  Locale _currentLocal;
  List<String> _themePaths;

  @override
  void initState() {
    super.initState();

    /// 这里进行业务模块注册，只需要注入注册表文件即可
    AppRouter.addModuleRoutes([
      // ModuleARegister(),
      // ModuleBRegister(),
      // ModuleCRegister()
    ]);
//    _currentLocal =  _languageConfig.supportLocale;
    _langInit();

    _themeInit();
  }

  void _themeInit() {
    String theme = SpUtil.getString("theme_model", defValue: "system");

    final Window window = WidgetsBinding.instance.window;

    window.onPlatformBrightnessChanged = WXTheme().themeChangedCallback;

//    window.onPlatformBrightnessChanged = () {
//      final brightness = window.platformBrightness;
//
//      print("brightness: $brightness");
//
//      WXTheme.setSystemTheme(brightness);
//
//      setState(() {
//
//      });
//    };

    _themePaths = ModulesConfig.packages
        .map((path) => "packages/$path/assets/theme/skin.json")
        .toList();

    WXTheme().init(
        paths: _themePaths,
        basicColorPath: "assets/theme/basic_colors.json",
        themeType: theme,
        current: window.platformBrightness);
  }

  /// 国际化初始化
  void _langInit() {
    /// 获取原有语言配置信息
    String lastLang = SpUtil.getString("lang_model");
    bool isFollowSystem = true;

    print("lastLang--SP--$lastLang");

    if (lastLang != null && lastLang.isNotEmpty) {
      switch (lastLang) {
        case "zh":
          isFollowSystem = false;
          _currentLocal = Locale("zh", "CH");
          break;

        case "en":
          isFollowSystem = false;
          _currentLocal = Locale("en", "US");
          break;

        default:
          isFollowSystem = true;

          break;
      }
    }

    _paths = ModulesConfig.packages
        .map((path) => "packages/$path/assets/lang/")
        .toList();

    WXLocales.init(_languageConfig ??= MainLangConfig(),
        first: _currentLocal, isFollowSystem: isFollowSystem);

    WXLocales.onLocaleChanged = onLocaleChange;

    _localeOverrideDelegate = new SpecificLocalizationDelegate(null);
  }

  onLocaleChange(Locale locale) {
    _currentLocal = locale;
    setState(() {
      _localeOverrideDelegate = new SpecificLocalizationDelegate(locale);
    });
  }

  @override
  Widget build(BuildContext context) {
    return OKToast(
      position: ToastPosition.bottom,
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Demo',
//        theme: ThemeData(
//          // primarySwatch: Colors.blue,
//            primaryColor: MaterialColor(0xFF000000, <int, Color>{
//              500: Color(0xFF000000),
//            })),
        initialRoute: '/WalletStartPage',
        // home: QRCodeScan(),
        navigatorKey: AppConfig.navigatorKey,
        onGenerateRoute: AppRouter.onGenerateRoute,

        /// 国际化
        localeResolutionCallback: WXLocales.localeResolutionCallback,

        ///
        localizationsDelegates: WXLocales.localizationsDelegates(
            AppLocalizationsDelegate(
                locale: _currentLocal, config: _languageConfig, paths: _paths),
            forceDelegate: _localeOverrideDelegate),

        ///
        supportedLocales: WXLocales.supportedLocales,

        ///　如果设置title的话需要用这个才可以实现title的国际化
//          onGenerateTitle: WXLocales.generateAppTitle,
//          theme: ThemeData(brightness: Brightness.light),
//          themeMode: WXTheme().systemTheme,
//          darkTheme: ThemeData(brightness: Brightness.dark),
        navigatorObservers: [BaseNavigationObserver()],
        // home: BiMoneyStartPage(),
      ),
    );
//    CoinManager().getListData();
  }
}
